首页 > 试题广场 >

加起来和为目标值的组合

[编程题]加起来和为目标值的组合
  • 热度指数:2864 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个无重复元素的正整数数组 nums 和一个正整数 target ,找出 nums 中所有可以使数字之和为目标数 target 的组合,nums 中的数可以重复选取,只要选出的组合中有一个数不同则视为是不同组合。


数据范围:数组长度满足 , 数组中的元素满足 ,保证组合数结果少于 150 个
示例1

输入

1,[1]

输出

[[1]]
示例2

输入

5,[1,4,5]

输出

[[1,4],[5],[1,1,1,1,1]]
示例3

输入

5,[2]

输出

[]
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param target int整型 
 * @param nums int整型一维数组 
 * @return int整型二维数组
 */
let result = []
function combinationCount( target ,  nums ) {
    // write code here
    let path = []
    dfs(nums,0,target,path)
    return result
}
function dfs(nums,start,res,path){
    if(res < 0) return
    if (res == 0) {
        result.push(path.slice())
        
    }
    else{
        for(let i = start ; i < nums.length ; i++){
            path.push(nums[i])
            dfs(nums ,i ,res - nums[i] , path)
            path.pop()
        }
    }
        
}
module.exports = {
    combinationCount : combinationCount
};
发表于 2022-01-20 00:59:23 回复(0)

问题信息

难度:
1条回答 2206浏览

热门推荐

通过挑战的用户

查看代码